<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Date &amp; time in Qt4</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Qt4 utility classes, tutorial, C++, programming, GUI, multiplatform, time, date">
<meta name="description" content="In this part of the Qt4 tutorial, we will work with time
and date">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-5536206-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content2">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Date and time in Qt4</h1>


<p>
In this part of the Qt4 C++ programming tutorial, we will talk about 
time and date. 
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
Qt4 has QDate, QTime and QDateTime classes to work with date and time.
The QDate is a class for working with a calendar date in the Gregorian
calendar. It has methods for determining the date, comparing or manipulating dates.
The QTime class works with a clock time. It provides methods for comparing
time, determining the time and various other time manipulating methods.
The QDateTime is a class that combines both QDate and QTime objects into
one object. 
</p>


<h2>Initializing date &amp; time objects</h2>

<p>
Date and time objects can be initialized in two basic ways. We initialize
them in the object constructor or we can create empty objects and
fill them with data later. 
</p>

<div class="codehead">init.cpp</div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QDate&gt;
#include &lt;QTime&gt;

int main(void)
{
   QTextStream out(stdout);

   QDate dt1(2011, 4, 12);
   out &lt;&lt; "The date is " &lt;&lt; dt1.toString() &lt;&lt; endl;
   
   QDate dt2;
   dt2.setDate(2011, 3, 3);
   out &lt;&lt; "The date is " &lt;&lt; dt2.toString() &lt;&lt; endl;

   QTime tm1(17, 30, 12, 55);
   out &lt;&lt; "The time is " &lt;&lt; tm1.toString("hh:mm:ss.zzz") &lt;&lt; endl;
   
   QTime tm2;
   tm2.setHMS(13, 52, 45, 155);
   out &lt;&lt; "The time is " &lt;&lt; tm2.toString("hh:mm:ss.zzz") &lt;&lt; endl;     
}
</pre>

<p>
We initialize date and time object in both ways.
</p>

<pre class="explanation">
QDate dt1(2011, 4, 12);
</pre>

<p>
The <code>QDate</code> object constructor takes three parameters. The
year, the month and the day. 
</p>

<pre class="explanation">
out &lt;&lt; "The date is " &lt;&lt; dt1.toString() &lt;&lt; endl;
</pre>

<p>
The date is printed to the console. We use the <code>toString()</code>
method to convert the date object into string.
</p>


<pre class="explanation">
QTime tm2;
tm2.setHMS(13, 52, 45, 155);
</pre>

<p>
An empty <code>QTime</code> object is created. We fill the object with data
using the <code>setHMS()</code> method. The parameters are the hours, minutes, seconds
and the miliseconds.
</p>

<pre class="explanation">
out &lt;&lt; "The time is " &lt;&lt; tm2.toString("hh:mm:ss.zzz") &lt;&lt; endl;   
</pre>

<p>
We print the <code>QTime</code> object to the console. We use a specific format that
includes also the miliseconds, which are omitted by default. 
</p>


<div class="codehead">Output</div>
<pre class="code">
$ ./simple 
The date is Tue Apr 12 2011
The date is Thu Mar 3 2011
The time is 17:30:12.055
The time is 13:52:45.155
</pre>


<h2>Current date &amp; time</h2>

<p>
In the following example, we print the current local time and date to the console. 
</p>

<div class="codehead">curdatetime.cpp</div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QTime&gt;
#include &lt;QDate&gt;

int main()
{
   QTextStream out(stdout);

   QDate cd = QDate::currentDate();
   QTime ct = QTime::currentTime();
   
   out &lt;&lt; "Current date is " &lt;&lt; cd.toString() &lt;&lt; endl;
   out &lt;&lt; "Current time is " &lt;&lt; ct.toString() &lt;&lt; endl;      
}
</pre>

<p>
Watch out that the file must not be called time.cpp. 
</p>

<pre class="explanation">
QDate cd = QDate::currentDate();
</pre>

<p>
The <code>QDate::currentDate()</code> static function returns the current date.
</p>

<pre class="explanation">
QTime ct = QTime::currentTime();
</pre>

<p>
The <code>QTime::currentTime()</code> static function returns the current time.
</p>

<pre class="explanation">
out &lt;&lt; "Current date is " &lt;&lt; cd.toString() &lt;&lt; endl;
out &lt;&lt; "Current time is " &lt;&lt; ct.toString() &lt;&lt; endl; 
</pre>

<p>
We use the <code>toString()</code> method to convert the date and time
objects to strings. 
</p>

<div class="codehead">Output</div>
<pre class="code">
$ ./curdatetime 
Current date is Tue Sep 18 2012
Current time is 19:43:37
</pre>


<h2>Comparing dates</h2>

<p>
Relational operators can be used to compare dates. 
We can compare their position in the calendar.
</p>

<div class="codehead">comparedates.cpp</div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QDate&gt;

int main()
{
   QTextStream out(stdout);

   QDate dt1(2012, 4, 5);
   QDate dt2(2011, 4, 5);
   
   if (dt1 &lt; dt2) {
       out &lt;&lt; dt1.toString() &lt;&lt; " comes before "
       &lt;&lt; dt2.toString() &lt;&lt; endl;
   } else {
       out &lt;&lt; dt1.toString() &lt;&lt; " comes after "
       &lt;&lt; dt2.toString() &lt;&lt; endl;
   }   
}
</pre>

<p>
The example compares two dates. 
</p>

<pre class="explanation">
QDate dt1(2012, 4, 5);
QDate dt2(2011, 4, 5);
</pre>

<p>
We have two different dates.
</p>

<pre class="explanation">
if (dt1 &lt; dt2) {
    out &lt;&lt; dt1.toString() &lt;&lt; " comes before "
    &lt;&lt; dt2.toString() &lt;&lt; endl;
} else {
    out &lt;&lt; dt1.toString() &lt;&lt; " comes after "
    &lt;&lt; dt2.toString() &lt;&lt; endl;
}   
</pre>

<p>
We compare the dates with a lower than (&lt;) comparison operator and 
determine which of them is located earlier in the calendar.
</p>


<div class="codehead">Output</div>
<pre class="code">
$ ./comparedates 
Thu Apr 5 2012 comes after Tue Apr 5 2011
</pre>

<p>
Comparison operators can be easily used for QTime and QDateTime objects too.
</p>


<h2>Determining a leap year</h2>

<p>
A <b>leap year</b> is a year containing an additional day. The reason for an extra day
in the calendar is the difference between the astronomical and the calendar year.
The calendar year has exactly 365 days, while the astronomical year, the time for 
the earth to make one revolution around the Sun, is 365.25 days.
The difference is 6 hours which means that in four years time we are missing one day. 
Because we want to have our calendar synchronized with the seasons, we add one
day to February each four years. (There are exceptions.) In the Gregorian calendar, February in a leap year 
has 29 days instead of the usual 28. And the year lasts 366 days instead of the usual 365. 
</p>

<p>
The <code>QDate::isLeapYear()</code> 
static method determines, whether a year is a leap year or not. 
</p>


<div class="codehead">leapyear.cpp</div>
<pre class="code">
#include &lt;QTextStream>
#include &lt;QDate>

int main()
{
   QTextStream out(stdout);

   
   if (QDate::isLeapYear(2010)) {
       out &lt;&lt; "2010 is a leap year" &lt;&lt; endl;
   } else {
       out &lt;&lt; "2010 is not a leap year" &lt;&lt; endl; 
   }
   
   if (QDate::isLeapYear(2011)) {
       out &lt;&lt; "2011 is a leap year" &lt;&lt; endl;
   } else {
       out &lt;&lt; "2011 is not a leap year" &lt;&lt; endl;
   }
   
   if (QDate::isLeapYear(2012)) {
       out &lt;&lt; "2012 is a leap year" &lt;&lt; endl;
   } else {
       out &lt;&lt; "2012 is not a leap year" &lt;&lt; endl;
   }         
}
</pre>

<p>
We check three years and print if they are leap years or not leap years.
</p>

<pre class="explanation">
if (QDate::isLeapYear(2010)) {
    out &lt;&lt; "2010 is a leap year" &lt;&lt; endl;
} else {
    out &lt;&lt; "2010 is not a leap year" &lt;&lt; endl; 
}
</pre>

<p>
Here we check if the year 2010 is a leap year. We print a message accordingly
to the terminal. The <code>QDate::isLeapYear()</code> returns a boolean true
or false. 
</p>


<div class="codehead">Output</div>
<pre class="code">
$ ./leapyear 
2010 is not a leap year
2011 is not a leap year
2012 is a leap year
</pre>


<h2>Predefined date formats</h2>

<p>
Qt4 has some built-in date formats. 
The <code>toString()</code> method of a <code>QDate</code>
object takes a date format as a parameter. The default
date format used by Qt4 is Qt::TextDate. 
</p>

<div class="codehead">dateformats.cpp</div>
<pre class="code">
#include &lt;QTextStream>
#include &lt;QDate>

int main(void)
{
   QTextStream out(stdout);

   QDate cd = QDate::currentDate();
   
   out &lt;&lt; "Today is " &lt;&lt; cd.toString(Qt::TextDate) &lt;&lt; endl;
   out &lt;&lt; "Today is " &lt;&lt; cd.toString(Qt::ISODate) &lt;&lt; endl;
   out &lt;&lt; "Today is " &lt;&lt; cd.toString(Qt::SystemLocaleShortDate) &lt;&lt; endl;
   out &lt;&lt; "Today is " &lt;&lt; cd.toString(Qt::SystemLocaleLongDate) &lt;&lt; endl;
   out &lt;&lt; "Today is " &lt;&lt; cd.toString(Qt::DefaultLocaleShortDate) &lt;&lt; endl;
   out &lt;&lt; "Today is " &lt;&lt; cd.toString(Qt::DefaultLocaleLongDate) &lt;&lt; endl;
   out &lt;&lt; "Today is " &lt;&lt; cd.toString(Qt::SystemLocaleDate) &lt;&lt; endl;
   out &lt;&lt; "Today is " &lt;&lt; cd.toString(Qt::LocaleDate) &lt;&lt; endl;   
}
</pre>

<p>
In the example, we show 8 different date formats for the current date. 
</p>

<pre class="explanation">
out &lt;&lt; "Today is " &lt;&lt; cd.toString(Qt::ISODate) &lt;&lt; endl;
</pre>

<p>
Here we print the current date in the Qt::ISODate format, which is an international
standard for displaying dates. 
</p>

<div class="codehead">Output</div>
<pre class="code">
$ ./dateformats 
Today is Wed Sep 19 2012
Today is 2012-09-19
Today is 9/19/12
Today is Wednesday, September 19, 2012
Today is 9/19/12
Today is Wednesday, September 19, 2012
Today is 9/19/12
Today is 9/19/12
</pre>


<h2>Custom date formats</h2>

<p>
A date can be represented in a variety of other formats. 
In Qt4 we can create our custom date formats. Another version
of the <code>toString()</code> method takes a format string where
we can use various format specifiers. For example the d specifier
stands for a day as a number without a leading zero. The dd specifier
stands for a day as a number with a leading zero. The following table
lists available date format expressions.
</p>

<table>
<thead>
<tr><th>Expression</th><th>Output</th></tr>
</thead>
<tbody>
<tr class="gray"><td>d</td><td>The day as a number without a leading zero (1 to 31)</td></tr>
<tr><td>dd</td><td>The day as a number with a leading zero (01 to 31)</td></tr>
<tr class="gray"><td>ddd</td><td>The abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses QDate::shortDayName().</td></tr>
<tr><td>dddd</td><td>The long localized day name (e.g. 'Monday' to 'Sunday'). Uses QDate::longDayName().</td></tr>
<tr class="gray"><td>M</td><td>The month as a number without a leading zero (1 to 12)</td></tr>
<tr><td>MM</td><td>The month as a number with a leading zero (01 to 12)</td></tr>
<tr class="gray"><td>MMM</td><td>The abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses QDate::shortMonthName().</td></tr>
<tr><td>MMMM</td><td>The long localized month name (e.g. 'January' to 'December'). Uses QDate::longMonthName().</td></tr>
<tr class="gray"><td>yy</td><td>The year as two digit number (00 to 99)</td></tr>
<tr><td>yyyy</td><td>The year as four digit number. If the year is negative, a minus sign is prepended in addition.</td></tr>
</tbody>
</table>

<div class="table">Table: Date format specifiers</div>

<div class="codehead">customdateformats.cpp</div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QDate&gt;

int main(void)
{
   QTextStream out(stdout);

   QDate cd = QDate::currentDate();
   
   out &lt;&lt; "Today is " &lt;&lt; cd.toString("yyyy-MM-dd") &lt;&lt; endl;
   out &lt;&lt; "Today is " &lt;&lt; cd.toString("yy/M/dd") &lt;&lt; endl;
   out &lt;&lt; "Today is " &lt;&lt; cd.toString("d.M.yyyy") &lt;&lt; endl;
   out &lt;&lt; "Today is " &lt;&lt; cd.toString("d-MMMM-yyyy") &lt;&lt; endl; 
}
</pre>

<p>
We have four custom date formats. 
</p>

<pre class="explanation">
out &lt;&lt; "Today is " &lt;&lt; cd.toString("yyyy-MM-dd") &lt;&lt; endl;
</pre>

<p>
This is the international date format. The parts of the date are separated by
a dash character. The yyyy is a year having four digits. The MM is the 
the month as number with a leading zero. (01 to 12) And the dd is the day as 
number with a leading zero (01 to 31). 
</p>

<pre class="explanation">
out &lt;&lt; "Today is " &lt;&lt; cd.toString("yy/M/dd") &lt;&lt; endl;
</pre>

<p>
This is another common date format. The parts are separated by a slash (/) character. 
The M specifier stands for a month as number without a leading zero (1 to 12).
</p>

<pre class="explanation">
out &lt;&lt; "Today is " &lt;&lt; cd.toString("d.M.yyyy") &lt;&lt; endl;
</pre>

<p>
This date format is used in Slovakia. The parts are separated by a dot character.
The day and month are without leading zeros. First is the day, then comes the month
and the last is the year. 
</p>


<div class="codehead">Output</div>
<pre class="code">
$ ./customdateformats 
Today is 2012-09-19
Today is 12/9/19
Today is 19.9.2012
Today is 19-September-2012
</pre>


<h2>Predefined time formats</h2>

<p>
Time has some predefined formats. The standard format
specifiers are identical to those used in the date formats.
The default time format used by Qt4 is Qt::TextDate. 
</p>

<div class="codehead">timeformats.cpp</div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QTime&gt;

int main(void)
{
   QTextStream out(stdout);

   QTime ct = QTime::currentTime();
   
   out &lt;&lt; "The time is " &lt;&lt; ct.toString(Qt::TextDate) &lt;&lt; endl;
   out &lt;&lt; "The time is " &lt;&lt; ct.toString(Qt::ISODate) &lt;&lt; endl;
   out &lt;&lt; "The time is " &lt;&lt; ct.toString(Qt::SystemLocaleShortDate) &lt;&lt; endl;
   out &lt;&lt; "The time is " &lt;&lt; ct.toString(Qt::SystemLocaleLongDate) &lt;&lt; endl;
   out &lt;&lt; "The time is " &lt;&lt; ct.toString(Qt::DefaultLocaleShortDate) &lt;&lt; endl;
   out &lt;&lt; "The time is " &lt;&lt; ct.toString(Qt::DefaultLocaleLongDate) &lt;&lt; endl;
   out &lt;&lt; "The time is " &lt;&lt; ct.toString(Qt::SystemLocaleDate) &lt;&lt; endl;
   out &lt;&lt; "The time is " &lt;&lt; ct.toString(Qt::LocaleDate) &lt;&lt; endl;   
}
</pre>

<p>
In the example, we show 8 different time formats for the current time. 
</p>

<pre class="explanation">
out &lt;&lt; "The time is " &lt;&lt; ct.toString(Qt::ISODate) &lt;&lt; endl;
</pre>

<p>
Here we print the current time in the Qt::ISODate format, which is an international
standard for displaying times. 
</p>

<div class="codehead">Output</div>
<pre class="code">
$ ./timeformats 
The time is 08:12:52
The time is 08:12:52
The time is 8:12 AM
The time is 8:12:52 AM CEST
The time is 8:12 AM
The time is 8:12:52 AM CEST
The time is 8:12 AM
The time is 8:12 AM
</pre>


<h2>Custom time formats</h2>

<p>
We can create additional time formats. We build a custom time
format where we use time format specifiers. The following
table gives a list of available format expressions.
</p>

<table>
<thead>
<tr>
<th>Expression</th><th>Output</th>
</tr>
</thead>
<tbody>
<tr class="gray"><td>h</td><td>the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)</td></tr>
<tr><td>hh</td><td>the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)</td></tr>
<tr class="gray"><td>H</td><td>the hour without a leading zero (0 to 23, even with AM/PM display)</td></tr>
<tr><td>HH</td><td>the hour with a leading zero (00 to 23, even with AM/PM display)</td></tr>
<tr class="gray"><td>m</td><td>the minute without a leading zero (0 to 59)</td></tr>
<tr><td>mm</td><td>the minute with a leading zero (00 to 59)</td></tr>
<tr class="gray"><td>s</td><td>the second without a leading zero (0 to 59)</td></tr>
<tr><td>ss</td><td>the second with a leading zero (00 to 59)</td></tr>
<tr class="gray"><td>z</td><td>the milliseconds without leading zeroes (0 to 999)</td></tr>
<tr><td>zzz</td><td>the milliseconds with leading zeroes (000 to 999)</td></tr>
<tr class="gray"><td>AP or A</td> <td>use AM/PM display. AP will be replaced by either "AM" or "PM".</td></tr>
<tr><td>ap or a</td><td>use am/pm display. ap will be replaced by either "am" or "pm".</td></tr>
<tr class="gray"><td>t</td><td>the timezone (for example "CEST")</td></tr>
</tbody>
</table>

<div class="table">Table: Time format specifiers</div>


<div class="codehead">customtimeformats.cpp</div>
<pre class="code">
#include &lt;QTextStream>
#include &lt;QTime>

int main(void)
{
   QTextStream out(stdout);

   QTime ct = QTime::currentTime();
   
   out &lt;&lt; "The time is " &lt;&lt; ct.toString("hh:mm:ss.zzz") &lt;&lt; endl;
   out &lt;&lt; "The time is " &lt;&lt; ct.toString("h:m:s a") &lt;&lt; endl;
   out &lt;&lt; "The time is " &lt;&lt; ct.toString("H:m:s A") &lt;&lt; endl;
   out &lt;&lt; "The time is " &lt;&lt; ct.toString("h:m AP") &lt;&lt; endl;  
   
   out &lt;&lt; "The version of Qt4 is " &lt;&lt; qVersion() &lt;&lt; endl;
}
</pre>

<p>
We have four custom time formats. 
</p>

<pre class="explanation">
out &lt;&lt; "The time is " &lt;&lt; ct.toString("hh:mm:ss.zzz") &lt;&lt; endl;
</pre>

<p>
In this format, we have the hour, minute and second with a leading zero. We also
add the milliseconds with leading zeroes. 
</p>

<pre class="explanation">
out &lt;&lt; "The time is " &lt;&lt; ct.toString("h:m:s a") &lt;&lt; endl;
</pre>

<p>
This time format specifier uses the hour, minute and second without a leading zero
and adds am/pm period identifiers.
</p>


<div class="codehead">Output</div>
<pre class="code">
$ ./customtimeformats 
The time is 08:45:19.295
The time is 8:45:19 am
The time is 8:45:19 AM 
The time is 8:45 AM
</pre>


<h2>Retrieving the weekday</h2>

<p>
The <code>dayOfWeek()</code> method returns a number which
represents a day of a week. Where 1 is Monday and 7 is Sunday.
</p>


<div class="codehead">weekday.cpp</div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QDate&gt;

int main()
{
   QTextStream out(stdout);

   QDate cd = QDate::currentDate();
   int wd = cd.dayOfWeek();
   
   out &lt;&lt; "Today is " &lt;&lt; QDate::shortDayName(wd) &lt;&lt; endl;
   out &lt;&lt; "Today is " &lt;&lt; QDate::longDayName(wd) &lt;&lt; endl;          
}
</pre>

<p>
In the example we print the short and long names of a current weekday. 
</p>

<pre class="explanation">
QDate cd = QDate::currentDate();
</pre>

<p>
We get the current date. 
</p>


<pre class="explanation">
int wd = cd.dayOfWeek();
</pre>

<p>
From the current date we get the day of week. 
</p>


<pre class="explanation">
out &lt;&lt; "Today is " &lt;&lt; QDate::shortDayName(wd) &lt;&lt; endl;
</pre>

<p>
With the <code>QDate::shortDayName()</code> static method we get the
short name of the weekday.
</p>

<pre class="explanation">
out &lt;&lt; "Today is " &lt;&lt; QDate::longDayName(wd) &lt;&lt; endl;    
</pre>

<p>
Using the <code>QDate::longDayName()</code> static method we get the
long name of the weekday.
</p>


<div class="codehead">Output</div>
<pre class="code">
$ ./weekday 
Today is Wed
Today is Wednesday
</pre>



<h2>Number of days</h2>

<p>
We can compute the number of days in a particular month using the 
<code>daysInMonth()</code> method and the number of days in a year
using the <code>daysInYear()</code> method.
</p>

<div class="codehead">nofdays.cpp</div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QDate&gt;

int main()
{
   QTextStream out(stdout);
   
   QDate dt1(2012, 9, 18);
   QDate dt2(2012, 2, 11);
   QDate dt3(2012, 5, 1);
   QDate dt4(2012, 12, 11);
   QDate dt5(2012, 1, 21);
   
   out &lt;&lt; "There are " &lt;&lt; dt1.daysInMonth() &lt;&lt; " days in " 
       &lt;&lt; QDate::longMonthName(dt1.month()) &lt;&lt; endl;      
   out &lt;&lt; "There are " &lt;&lt; dt2.daysInMonth() &lt;&lt; " days in " 
       &lt;&lt; QDate::longMonthName(dt2.month()) &lt;&lt; endl;
   out &lt;&lt; "There are " &lt;&lt; dt3.daysInMonth() &lt;&lt; " days in " 
       &lt;&lt; QDate::longMonthName(dt3.month()) &lt;&lt; endl;
   out &lt;&lt; "There are " &lt;&lt; dt4.daysInMonth() &lt;&lt; " days in " 
       &lt;&lt; QDate::longMonthName(dt4.month()) &lt;&lt; endl;
   out &lt;&lt; "There are " &lt;&lt; dt5.daysInMonth() &lt;&lt; " days in " 
       &lt;&lt; QDate::longMonthName(dt5.month()) &lt;&lt; endl;
     
   out &lt;&lt; "There are " &lt;&lt; dt1.daysInYear() &lt;&lt; " days in year " 
       &lt;&lt; QString::number(dt1.year()) &lt;&lt; endl;         
}
</pre>

<p>
Five date objects are created. We compute the number of days in those
months and in a particular year.
</p>


<pre class="explanation">
QDate dt1(2012, 9, 18);
QDate dt2(2012, 2, 11);
QDate dt3(2012, 5, 1);
QDate dt4(2012, 12, 11);
QDate dt5(2012, 1, 21);
</pre>

<p>
Five <code>QDate</code> objects are created. Each of them represents
a different date. 
</p>


<pre class="explanation">
out &lt;&lt; "There are " &lt;&lt; dt1.daysInMonth() &lt;&lt; " days in " 
    &lt;&lt; months.at(dt1.month()-1) &lt;&lt; endl;   
</pre>

<p>
We use the <code>daysInMonth()</code> method to get the number of days
in the date object.
</p>

<pre class="explanation">
out &lt;&lt; "There are " &lt;&lt; dt1.daysInYear() &lt;&lt; " days in year " 
    &lt;&lt; QString::number(dt1.year()) &lt;&lt; endl;      
</pre>

<p>
And here, we get the number of days in a year using the <code>daysInYear()</code>
method for the date object. 
</p>


<div class="codehead">Output</div>
<pre class="code">
$ ./nofdays 
There are 30 days in September
There are 29 days in February
There are 31 days in May
There are 31 days in December
There are 31 days in January
There are 366 days in year 2012
</pre>


<h2>Checking validity of a date</h2>

<p>
There is a <code>isValid()</code> method which checks whether 
a date is valid or not.
</p>


<div class="codehead">isvalid.cpp</div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QDate&gt;

int main(void)
{
   QTextStream out(stdout);

   QDate dt1(2012, 5, 11);  
   QDate dt2(2012, 8, 1);
   QDate dt3(2012, 2, 30);
   
   if (dt1.isValid()) {
       out &lt;&lt; "The first date is valid" &lt;&lt; endl;
   } else {
       out &lt;&lt; "The first date is not valid" &lt;&lt; endl;
   }
   
   if (dt2.isValid()) {
       out &lt;&lt; "The second date is valid" &lt;&lt; endl;
   } else {
       out &lt;&lt; "The second date is not valid" &lt;&lt; endl;
   }
   
   if (dt3.isValid()) {
       out &lt;&lt; "The third date is valid" &lt;&lt; endl;
   } else {
       out &lt;&lt; "The third date is not valid" &lt;&lt; endl;
   }      
}
</pre>

<p>
In the example we check the validity of three days. 
</p>

<pre class="explanation">
QDate dt1(2012, 5, 11);  
QDate dt2(2012, 8, 1);
QDate dt3(2012, 2, 30);
</pre>

<p>
The first two days are valid. The third one is invalid. February
has 28 or 29 days. 
</p>


<pre class="explanation">
if (dt1.isValid()) {
    out &lt;&lt; "The first date is valid" &lt;&lt; endl;
} else {
    out &lt;&lt; "The first date is not valid" &lt;&lt; endl;
}
</pre>

<p>
Depending on the outcome of the <code>isValid()</code> method, we 
print a message about a validity of a date to the console.
</p>


<div class="codehead">Output</div>
<pre class="code">
$ ./isvalid 
The first date is valid
The second date is valid
The third date is not valid
</pre>


<h2>Days to, days from</h2>

<p>
We can easily calculate a date n days from a 
particular date. We use the <code>addDays()</code> method. 
The <code>daysTo()</code> method returns the number of days
to a chosen date. 
</p>


<div class="codehead">daystofrom.cpp</div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QDate&gt;

int main(void)
{
   QTextStream out(stdout);

   QDate dt(2012, 5, 11);  
   QDate nd = dt.addDays(55);
   
   QDate xmas(2012, 12, 24);
   
   out &lt;&lt; "55 days from " &lt;&lt; dt.toString() &lt;&lt; " is " 
       &lt;&lt; nd.toString() &lt;&lt; endl;   
   out &lt;&lt; "There are " &lt;&lt; QDate::currentDate().daysTo(xmas) 
       &lt;&lt; " days till Christmas" &lt;&lt; endl;       
}
</pre>

<p>
We get a date 55 day later from May 11, 2012. We also get the number of days
till Christmas. 
</p>

<pre class="explanation">
QDate dt(2012, 5, 11);  
QDate nd = dt.addDays(55);
</pre>

<p>
The <code>addDays()</code> method returns a <code>QDate</code> which is 55
days after May 11, 2012. 
</p>


<pre class="explanation">
QDate xmas(2012, 12, 24);
...
out &lt;&lt; "There are " &lt;&lt; QDate::currentDate().daysTo(xmas) 
    &lt;&lt; " days till Christmas" &lt;&lt; endl; 
</pre>

<p>
We use the <code>daysTo()</code> method to calculate the number of 
days until Christmas.
</p>

<div class="codehead">Output</div>
<pre class="code">
$ ./daystofrom 
55 days from Fri May 11 2012 is Thu Jul 5 2012
There are 96 till Christmas
</pre>


<h2>QDateTime class</h2>

<p>
The <code>QDateTime</code> object contains a calendar date and a clock time. 
It is a combination of the <code>QDate</code> and <code>QTime</code> classes. 
It has many similar methods and the usage is identical to those two classes.
</p>


<div class="codehead">datetime.cpp</div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QDateTime&gt;

int main()
{
   QTextStream out(stdout);

   QDateTime cdt = QDateTime::currentDateTime();   
   
   out &lt;&lt; "The current datetime is " &lt;&lt; cdt.toString() &lt;&lt; endl;
   out &lt;&lt; "The current date is " &lt;&lt; cdt.date().toString() &lt;&lt; endl;
   out &lt;&lt; "The current time is " &lt;&lt; cdt.time().toString() &lt;&lt; endl;   
}
</pre>

<p>
The example retrieves the current datetime. 
</p>

<pre class="explanation">
out &lt;&lt; "The current datetime is " &lt;&lt; cdt.toString() &lt;&lt; endl;
</pre>

<p>
This line of code prints the current datetime to the terminal.
</p>

<pre class="explanation">
out &lt;&lt; "The current date is " &lt;&lt; cdt.date().toString() &lt;&lt; endl;
</pre>

<p>
This line retrieves the date portion of the datetime object using the <code>date()</code>
method.
</p>

<div class="codehead">Output</div>
<pre class="code">
$ ./datetime 
The current datetime is Thu Sep 20 09:51:22 2012
The current date is Thu Sep 20 2012
The current time is 09:51:22
</pre>


<h2>UTC time</h2>

<p>
Our planet is a sphere. It revolves round its axis. The Earth rotates towards the east.
So the Sun rises at different times in different locations. The Earth rotates 
once in about 24 hours. Therefore, the world was divided into 24 time zones. In each
time zone, there is a different local time. This local time is often further modified
by the daylight saving. 
</p>

<p>
There is a pragmatic need for one global time. One global time helps to avoid confusion 
about time zones and daylight saving time. The UTC (Universal Coordinated time) 
was chosen to be the primary time standard. UTC is used in aviation, weather 
forecasts, flight plans, air traffic control clearances and maps. Unlike local time, 
UTC does not change with a change of seasons.
</p>

<div class="codehead">utclocal.cpp</div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QDateTime&gt;

int main(void)
{
  QTextStream out(stdout);
   
  QDateTime cdt = QDateTime::currentDateTime();   
  
  out &lt;&lt; "Universal datetime" &lt;&lt; cdt.toUTC().toString() &lt;&lt; endl;
  out &lt;&lt; "Local datetime" &lt;&lt; cdt.toLocalTime().toString() &lt;&lt; endl;
}
</pre>

<p>
In the example we compute the current datetime. We express the datetime in UTC datetime
and local datetime.
</p>

<pre class="explanation">
out &lt;&lt; "Universal datetime" &lt;&lt; cdt.toUTC().toString() &lt;&lt; endl;
</pre>

<p>
The <code>toUTC()</code> method is used to get the UTC datetime.
</p>

<pre class="explanation">
out &lt;&lt; "Local datetime" &lt;&lt; cdt.toLocalTime().toString() &lt;&lt; endl;
</pre>

<p>
The <code>toLocalTime()</code> is used to get the local datetime.
</p>


<div class="codehead">Output</div>
<pre class="code">
$ ./localutc 
Universal datetime: Thu Sep 20 09:20:34 2012
Local datetime: Thu Sep 20 11:20:34 2012
</pre>

<p>
The example was run in the UTC+1 hour time zone. Plus there is a additional
+1 hour for the daylight saving time.
</p>


<h2>The Unix epoch</h2>

<p>
An epoch is an instant in time chosen as the origin of a particular era. 
For example in western Christian countries the time epoch starts from 
day 0, when Jesus was born (is believed to be born). Another example is
the French Republican Calendar which was used for twelve years. The epoch
was the beginning of the Republican Era which was proclaimed on 
September 22, 1792, the day the First Republic was declared and the
monarchy abolished. Computers have their epochs too. One of the 
most popular is the Unix time. The Unix epoch is the time 00:00:00 UTC 
on 1 January 1970 (or 1970-01-01T00:00:00Z ISO 8601).
The date and time in a computer is determined according to the number of 
seconds or clock ticks that have elapsed since the defined epoch for 
that computer or platform. 
</p>

<pre>
$ date +%s
1348171197
</pre>

<p>
Unix date command can be used to get the Unix time. At this particular
moment, 1348171197 seconds have passed since the Unix epoch.
</p>

<div class="codehead"></div>
<pre class="code">
#include &lt;QTextStream&gt;
#include &lt;QDateTime&gt;
#include &lt;ctime&gt;

int main()
{
  QTextStream out(stdout);

  time_t t = time(0);  
  out &lt;&lt; t &lt;&lt; endl;
  
  QDateTime dt;
  dt.setTime_t(t);
  out &lt;&lt; dt.toString() &lt;&lt; endl;
  
  QDateTime cd = QDateTime::currentDateTime();
  out &lt;&lt; cd.toTime_t() &lt;&lt; endl;       
}
</pre>

<p>
In the example, we use two Qt4 functions to get the Unix
time and convert it to the human readable form.
</p>

<pre class="explanation">
#include &lt;ctime&gt;
</pre>

<p>
We include the standard C++ time header file.
</p>

<pre class="explanation">
time_t t = time(0);  
out &lt;&lt; t &lt;&lt; endl;
</pre>

<p>
With the standard C++ time() command, we get the Unix
time. 
</p>

<pre class="explanation">
QDateTime dt;
dt.setTime_t(t);
out &lt;&lt; dt.toString() &lt;&lt; endl;
</pre>

<p>
The <code>setTime_t()</code> method is used to convert
the Unix time into the DateTime, which is formatted to
human readable form. 
</p>

<pre class="explanation">
QDateTime cd = QDateTime::currentDateTime();
out &lt;&lt; cd.toTime_t() &lt;&lt; endl; 
</pre>

<p>
The Qt4's <code>toTime_t()</code> method can be also
used to get the Unix time.
</p>


<div class="codehead">Output</div>
<pre class="code">
$ ./unixepoch 
1348171451
Thu Sep 20 22:04:11 2012
1348171451
</pre>


<p>
In this chapter, we have worked with time and date. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified September 21, 2012  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

